{% extends 'base.html' %}
{% block title %}{{ book.title }} - 图书详情{% endblock %}
{% block content %}
<div class="cards-row" style="gap:32px;align-items:flex-start;">
    <div class="info-card" style="max-width:320px;min-width:220px;text-align:center;">
        {% if book.cover %}
            <img src="{{ book.cover.url }}" alt="封面" style="width:80%;max-width:180px;border-radius:10px;margin-bottom:16px;box-shadow:0 2px 8px #2563eb22;">
        {% else %}
            <div style="width:100%;height:180px;background:#e0e7ef;border-radius:10px;display:flex;align-items:center;justify-content:center;font-size:3rem;color:#b0bec5;margin-bottom:16px;">📖</div>
        {% endif %}
        <div class="info-card-title" style="font-size:1.18rem;">{{ book.title }}</div>
        <div class="info-item"><b>作者：</b>{{ book.author }}</div>
        <div class="info-item"><b>ISBN：</b>{{ book.isbn }}</div>
        <div class="info-item"><b>分类：</b>{{ book.category|default:'--' }}</div>
        <div class="info-item"><b>标签：</b>{% for tag in book.tags|default:''|split:',' %}<span class="tag">{{ tag }}</span>{% empty %}--{% endfor %}</div>
        <div class="info-item"><b>借阅总次数：</b>{{ book.borrowed_count|default:'--' }}</div>
        <div class="info-item"><b>评分：</b>
            <span class="stars">
                {% for i in "12345" %}
                    {% if book.rating|float >= i|add:'0.5' %}<span class="star">★</span>{% elif book.rating|float >= i %}<span class="star">★</span>{% else %}<span class="star star-empty">★</span>{% endif %}
                {% endfor %}
            </span>
            <span style="color:#888;font-size:0.98rem;">({{ book.rating|floatformat:1 }}分/{{ book.rating_count }}人)</span>
        </div>
        {% if book.buy_link %}
        <div style="margin-top:10px;"><a href="{{ book.buy_link }}" target="_blank" class="btn btn-warning">去购买</a></div>
        {% endif %}
        <div class="info-item">
            <button id="favorite-btn" class="btn btn-pink" style="padding:6px 18px;" onclick="toggleFavorite({{ book.id }})">
                {% if user.is_authenticated and book.bookfavorite_set.filter(user=user).exists %}已收藏{% else %}收藏{% endif %}
            </button>
            <span id="favorite-count" style="color:#e91e63;font-weight:bold;margin-left:8px;">{{ book.favorite_count }}</span> 人收藏
        </div>
        <div class="info-item">
            <button id="like-btn" class="btn btn-success" style="padding:6px 18px;" onclick="toggleLike({{ book.id }})">
                👍 点赞
            </button>
            <span id="like-count" style="color:#22c55e;font-weight:bold;margin-left:8px;">{{ book.like_count }}</span> 人点赞
        </div>
    </div>
    <div class="info-card" style="flex:1 1 0%;min-width:220px;">
        <div class="info-item"><b>简介：</b>{{ book.summary }}</div>
        <h2 style="margin-top:18px;">馆藏情况</h2>
        <table>
            <tr>
                <th>版本信息</th>
                <th>到期日</th>
                <th>状态</th>
                <th>借阅者</th>
            </tr>
            {% for inst in instances %}
            <tr>
                <td>{{ inst.imprint }}</td>
                <td>{{ inst.due_back }}</td>
                <td>{% if inst.status == 'a' %}可借阅{% elif inst.status == 'o' %}已借出{% elif inst.status == 'm' %}维护中{% elif inst.status == 'r' %}已预订{% endif %}</td>
                <td>{% if inst.borrower %}{{ inst.borrower.username }}{% else %}-{% endif %}</td>
            </tr>
            {% endfor %}
        </table>
        {% if user.is_authenticated %}
            <form method="post" style="margin-top:16px;display:inline-block;">
                {% csrf_token %}
                {% if can_borrow %}
                    <button type="submit" name="action" value="borrow" class="btn btn-success">借阅</button>
                {% elif user_borrowed %}
                    <button type="submit" name="action" value="return" class="btn btn-warning">归还</button>
                {% endif %}
            </form>
        {% else %}
            <p>请先<a href="{% url 'login' %}">登录</a>后进行借阅操作。</p>
        {% endif %}
        <p><a href="{% url 'book-search' %}" class="btn btn-outline">返回搜索</a></p>
        <hr style="margin:24px 0;">
        <h2>评分与评论</h2>
        {% if user.is_authenticated %}
            <form method="post" style="margin-bottom:18px;display:flex;align-items:center;gap:18px;" action="">
                {% csrf_token %}
                {{ rating_form.score }}
                <button type="submit" name="rate" class="btn btn-info" style="padding:6px 18px;">提交评分</button>
                {% if user_rating %}<span style="color:#888;">你已评分：{{ user_rating.score }}星</span>{% endif %}
            </form>
            <form method="post" style="margin-bottom:18px;" action="">
                {% csrf_token %}
                {{ review_form.content }}
                <button type="submit" name="review" class="btn btn-success" style="padding:6px 18px;">发表评论</button>
            </form>
        {% else %}
            <p>请<a href="{% url 'login' %}">登录</a>后参与评分和评论。</p>
        {% endif %}
        <div style="margin-top:18px;">
            {% for review in reviews %}
                <div class="review-card">
                    <span class="review-author">{{ review.user.username }}</span>
                    <span class="review-date">{{ review.created_at|date:'Y-m-d H:i' }}</span>
                    <div class="review-content">{{ review.content }}</div>
                    <div class="review-actions">
                        <span class="like" onclick="likeReview({{ review.id }}, this)">👍 <span class="like-count">{{ review.like_count }}</span></span>
                        <span class="reply" onclick="showReplyBox({{ review.id }})">💬 回复</span>
                    </div>
                </div>
                <div class="reply-box" id="reply-box-{{ review.id }}" style="display:none;margin-top:8px;">
                    <textarea rows="2" style="width:90%;border-radius:6px;" placeholder="回复内容..."></textarea>
                    <button class="btn btn-info" style="padding:4px 16px;margin-left:8px;" onclick="submitReply({{ review.id }}, this)">发送</button>
                </div>
                <div class="review-replies" id="replies-{{ review.id }}">
                    {% for reply in review.replies.all %}
                        <div class="review-card" style="background:#f3f6fa;margin:8px 0 0 24px;padding:10px 14px;">
                            <span class="review-author">{{ reply.user.username }}</span>
                            <span class="review-date">{{ reply.created_at|date:'Y-m-d H:i' }}</span>
                            <div class="review-content">{{ reply.content }}</div>
                        </div>
                    {% endfor %}
                </div>
            {% empty %}
                <div style="color:#888;">暂无评论，快来发表你的看法吧！</div>
            {% endfor %}
        </div>
        <div style="margin-bottom:18px;">
            <button class="btn btn-info" onclick="showAISummaryDialog()">AI生成摘要</button>
        </div>
        <div id="ai-summary-dialog" style="display:none;position:fixed;top:0;left:0;width:100vw;height:100vh;background:#0003;z-index:1000;align-items:center;justify-content:center;">
            <div style="background:#fff;padding:32px 24px;border-radius:12px;max-width:420px;width:90vw;box-shadow:0 4px 32px #0002;position:relative;">
                <span style="position:absolute;top:10px;right:18px;cursor:pointer;font-size:1.3rem;" onclick="closeAISummaryDialog()">×</span>
                <h3>AI生成书籍摘要</h3>
                <div style="color:#888;font-size:0.98rem;margin-bottom:8px;">书名：<b>{{ book.title }}</b></div>
                <button class="btn btn-success" style="padding:6px 18px;" onclick="askAISummary()">生成摘要</button>
                <div id="ai-summary-answer" style="margin-top:16px;color:#2563eb;"></div>
            </div>
        </div>
    </div>
</div>
<script>
function likeReview(reviewId, btn) {
    fetch("{% url 'like-review' %}", {
        method: 'POST',
        headers: {
            'X-CSRFToken': '{{ csrf_token }}',
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: 'review_id=' + reviewId
    })
    .then(res => res.json())
    .then(data => {
        if(data.success) {
            btn.querySelector('.like-count').textContent = data.like_count;
        } else {
            alert(data.msg || '点赞失败');
        }
    });
}
function showReplyBox(id) {
    document.getElementById('reply-box-' + id).style.display = 'block';
}
function submitReply(id, btn) {
    const box = document.getElementById('reply-box-' + id);
    const textarea = box.querySelector('textarea');
    const content = textarea.value.trim();
    if(!content) { alert('回复内容不能为空'); return; }
    fetch("{% url 'reply-review' %}", {
        method: 'POST',
        headers: {
            'X-CSRFToken': '{{ csrf_token }}',
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: 'review_id=' + id + '&content=' + encodeURIComponent(content)
    })
    .then(res => res.json())
    .then(data => {
        if(data.success) {
            const repliesDiv = document.getElementById('replies-' + id);
            const html = `<div class='review-card' style='background:#f3f6fa;margin:8px 0 0 24px;padding:10px 14px;'><span class='review-author'>${data.reply.user}</span><span class='review-date'>${data.reply.created_at}</span><div class='review-content'>${data.reply.content}</div></div>`;
            repliesDiv.innerHTML += html;
            textarea.value = '';
            box.style.display = 'none';
        } else {
            alert(data.msg || '回复失败');
        }
    });
}
function toggleFavorite(bookId) {
    fetch("{% url 'toggle-favorite' %}", {
        method: 'POST',
        headers: {
            'X-CSRFToken': '{{ csrf_token }}',
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: 'book_id=' + bookId
    })
    .then(res => res.json())
    .then(data => {
        if(data.success) {
            document.getElementById('favorite-count').textContent = data.favorite_count;
            document.getElementById('favorite-btn').textContent = data.favorited ? '已收藏' : '收藏';
        } else {
            alert(data.msg || '操作失败');
        }
    });
}
function toggleLike(bookId) {
    fetch("{% url 'toggle-like' %}", {
        method: 'POST',
        headers: {
            'X-CSRFToken': '{{ csrf_token }}',
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: 'book_id=' + bookId
    })
    .then(res => res.json())
    .then(data => {
        if(data.success) {
            document.getElementById('like-count').textContent = data.like_count;
            document.getElementById('like-btn').textContent = data.liked ? '👍 已点赞' : '👍 点赞';
        } else {
            alert(data.msg || '操作失败');
        }
    });
}
function showAISummaryDialog() {
    document.getElementById('ai-summary-dialog').style.display = 'flex';
}
function closeAISummaryDialog() {
    document.getElementById('ai-summary-dialog').style.display = 'none';
    document.getElementById('ai-summary-answer').textContent = '';
}
function askAISummary() {
    document.getElementById('ai-summary-answer').textContent = 'AI思考中...';
    fetch("{% url 'ai-book-summary' %}", {
        method: 'POST',
        headers: {
            'X-CSRFToken': '{{ csrf_token }}',
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: 'book_title=' + encodeURIComponent("{{ book.title }}")
    })
    .then(res => res.json())
    .then(data => {
        document.getElementById('ai-summary-answer').textContent = data.summary || 'AI未能生成摘要';
    });
}
</script>
{% endblock %} 